//
//  WBUserAccount.swift
//  weibo
//
//  Created by wenquan wang on 12/12/16.
//  Copyright © 2016 wenquan wang. All rights reserved.
//

import UIKit

class WBUserAccount: NSObject {
    var access_token: String? //= "2.00bhxJdGZukQrC71e3c98fe3nS47rB"
    var uid: String?
    var expires_in: TimeInterval = 0.0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate: Date?
    
    var screen_name: String?
    
    var avatar_large: String?
    
    override init(){
        super.init()
        
        guard let path = (accountFile as NSString).cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: String]
        else{
                return
        }
        yy_modelSet(with: dict ?? [:])
        print("sandbox get userAccount\(self)")
        
        if(expiresDate?.compare(Date(timeIntervalSinceNow: 0)) != .orderedDescending){
            print("account token expired!")
            access_token = nil
            uid = nil
            _ = try? FileManager.default.removeItem(atPath: path)
            
            print("account token is valid !")
        }
        
    }
    
    override var description: String{
        return yy_modelDescription()
    }
    func expiresDateStr()->String{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
        return dateFormatter.string(from:(expiresDate ?? Date()))
    }
    /**
     * 
    */
    func saveAccount(){
        
        let dict:[String: String] = ["access_token":self.access_token ?? "", "uid":"\(self.uid ?? "")","expiresDate": expiresDateStr(),
                                     "screen_name":self.screen_name ?? "", "avatar_large":self.avatar_large ?? ""]
        
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted),
            let filePath = (accountFile as NSString).cz_appendDocumentDir()
            else{
                return
        }
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("user account is saved! \(filePath)")
        
    }
}
//var accessToken: String? //= "2.00bhxJdGZukQrC71e3c98fe3nS47rB"
//var uid: String? = "5365823342"
